package com.example.myapplication2;

import java.nio.*;
import java.nio.channels.*;
import java.util.*;
import java.lang.*;
import java.net.InetSocketAddress;

public class touc {
    public static void main(String[] args) throws Exception {
    }
    public static void work(logClass lo) throws Exception {
        byte[] id = helpFunc.getuuid_byte();
        byte[] encodedBytes = Base64.getEncoder().encode(id);
        myBuf tt = new myBuf(encodedBytes);
        int keyLen = (helpFunc.con_connBufSize/1024)%10+2;
        byte[] k = tt.readArr(keyLen);
        helpFunc.con_key = k;
        myBuf w = new myBuf(2000);
        w.writeArr(helpFunc.con_serverKey);
        w.writeArr(id);
        w.writeDWord(helpFunc.con_portsNum);
        w.writeByte(keyLen);
        w.writeArr(k);
        w.writeDWord(helpFunc.con_maxConn);
        w.writeDWord(helpFunc.con_cachePerConn);
        w.writeDWord(helpFunc.con_ssPort);
        w.writeDWord(helpFunc.serverPackLen);
        w.writeDWord(helpFunc.serverSenLen);
        w.writeDWord(helpFunc.con_connBufSize);
        double ef = helpFunc.con_packEffectTime / 1000.0;
        double timeout = helpFunc.con_timeoutInternal / 1000.0;
        w.writeDouble(ef);
        w.writeDouble(timeout);
        LinkedList<Integer> ports = new LinkedList<Integer>();
        while (true) {
            DatagramChannel so = DatagramChannel.open();
            InetSocketAddress add = new InetSocketAddress(helpFunc.serverIp, helpFunc.server_port);
            helpFunc.udpWrite(so, w.get(), add);
            Selector selector = Selector.open();
            so.configureBlocking(false);
            so.register(selector, SelectionKey.OP_READ);
            int ret = selector.select(1000);
            Iterator selectedKeys = selector.selectedKeys().iterator();
            boolean find = false;
            while (selectedKeys.hasNext()) {
                SelectionKey key = (SelectionKey) selectedKeys.next();
                selectedKeys.remove();
                if (!key.isValid()) {
                    continue;
                }
                if (key.channel() == so && key.isReadable())
                    find = true;
            }
            selector.close();
            if (!find) {
                so.close();
                continue;
            }
            byte[] aa = helpFunc.udpRead(so);
            so.close();
            myBuf w2 = new myBuf(aa);
            if (!helpFunc.arrayEqu(id, w2.readArr(16)))
                continue;

            for (int i = 0; i < helpFunc.con_portsNum; i++)
                ports.add(w2.readWord());
            helpFunc.print("server starts");
            break;
        }
        connc.enter(ports, lo);
    }
}
